package com.handinfo.android;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.CopyOnWriteArrayList;

import android.app.Activity;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageItemInfo;
import android.graphics.Canvas;
import android.net.TrafficStats;
import android.os.Handler;
import android.view.SurfaceView;
import android.widget.SeekBar;
import android.widget.Toast;

import com.handinfo.android.core.graphics.DWFont;
import com.handinfo.android.core.graphics.DWGraphics;
import com.handinfo.android.core.graphics.DWScreen;
import com.handinfo.android.core.input.DWInputView;
import com.handinfo.android.core.media.DWAudio;
import com.handinfo.android.core.net.BaseConnection;
import com.handinfo.android.core.net.GameProtocol;
import com.handinfo.android.core.net.IConnectionHandler;
import com.handinfo.android.core.object.IGameHandler;
import com.handinfo.android.core.object.Scene;
import com.handinfo.android.core.object.Scene.SceneHandler;
import com.handinfo.android.core.resource.IORWFile;
import com.handinfo.android.core.resource.ResHead;
import com.handinfo.android.core.resource.Resource;
import com.handinfo.android.core.resource.ResourceList;
import com.handinfo.android.core.resource.ResourceManager;
import com.handinfo.android.core.resource.ResourceVerifier;
import com.handinfo.android.core.ui.DWToast;
import com.handinfo.android.download.DWDownloadManager;
import com.handinfo.android.game.GameMessage;
import com.handinfo.android.game.Loading;
import com.handinfo.android.game.Login;
import com.handinfo.android.game.Role;
import com.handinfo.android.game.item.Item;
import com.handinfo.android.test.Test;
import com.handinfo.android.ui.ChatItem;
import com.handinfo.android.ui.UIWindows;
import com.handinfo.android.uicontrols.DWControlsManager;
import com.handinfo.android.uicontrols.DWExternalDraw;
import com.handinfo.android.uicontrols.DWListener;
import com.handinfo.android.uicontrols.controls.DWImageBox;
import com.handinfo.android.uicontrols.controls.DWMessageBox;
//import com.handinfo.android.utils.ChannelOperation;
import com.handinfo.android.utils.DWChannel;
import com.handinfo.android.utils.Tools;

public class DWGameManager implements Runnable, IConnectionHandler
{
	public String m_redundance; //用户登录时的冗余字段
	public String m_rolename = null; //登入时的用户名
	/** 单态实例句柄 */
	private static DWGameManager sInstance;
	private static DWScreen m_screen;

	/** 游戏当前流量总计 */
	public static long s_traffic_amount_last;

	/** 切换角色 */

	public static boolean s_change_role = false;

	/** 下载管理器 **/
	private DWDownloadManager m_download_manager;

	/** 画布 */
	public Role m_role = null;// 自己
	public int m_role_x;
	public int m_role_y;
	/**
	 * 内容 （如：Scene，Login等）
	 */
	private IGameHandler m_gamehandler;

	public boolean m_isPainting = true;

	private Handler handler = new Handler();

	public static long s_worldTimeServer = 0;
	public static long s_worldTimeDelay = 0;
	/**
	 * 连接
	 */
	protected BaseConnection m_connection;
	// ////////////////////////////////////////////////////////////////////
	// // 资源相关
	public Resource m_resourceDynamic; // 游戏动态资源，例如：地图，角色，场景NPC，怪物等
	public Resource m_resourceStatic; // 游戏静态资源，例如：UI， 战斗光效，图标等

	// //场景相关
	public String m_stage = null;// 场景ID
	public String m_map_name = null;// 地图名字
	public int m_scene_type; //场景安全区，非安全区等
	public byte m_scene_pk;//场景专属 0普通 1PK

	public ResourceList m_sceneResList = new ResourceList(); // 场景资源列表
	public ResHead mSceneResHead; //场景资源名

	/** 线程 */
	private Thread m_thread;
	/** 是否在运行 */
	private boolean m_running = true;
	/** 是否暂停 */
	private boolean m_pause = false;
	/** 帧计数器 */
	public long m_frameCounter;

	private GameMessage m_sendMessage = new GameMessage();

	/** 游戏画面像素尺寸 */
	public static int Screen_Width = 800;
	public static int Screen_Height = 480;

	/** 游戏适配类型 */
	public static byte AdpaterType = 1;
	public static final byte AD_HIGH = 2;
	public static final byte AD_MIDDLE = 1;
	public static final byte AD_LOW = 1;
	public static int AdpaterValue = 0;//

	/** 是否已经下载过半安装信息 */
	public static boolean Half_res = false;//0还未下载 1已下载过

	/** 屏幕方向 */
	public static boolean Screen_Landscape = true;

	/** 当前Activity */
	private DWGameActivity m_currentActivity;

	/** 游戏状态 **/
	public static final int GS_TEST = -1;
	public static final int GS_GAME = 0; // 游戏
	public static final int GS_LOADING = 1;
	public static final int GS_LOGIN = 2;
	public static final int GS_LOGO = 3;
	public static final int GS_RESOURCE = 4;

	/** 状态控制 */
	public int m_gameState = GS_RESOURCE;

	/** 时间相关 */
	public static final long SECOND = 1000;

	public static final long MINUTE = SECOND * 60;

	public static final long HOUR = MINUTE * 60;

	public static final long DAY = HOUR * 24;

	public static final long WEEK = DAY * 7;

	public static final long YEAR = DAY * 365;

	/** 帧间隔 */
	public static final int FRAME_INTERVAL = 100;

	/** 每秒帧数 */
	public static final int FRAME_PER_SECOND = 1000 / FRAME_INTERVAL;

	/** 编码方式 */
	public static final String ENDODING = "UTF-8";

	/** 字体（一般） */
	public static final String FONT_COMMON = "Monospaced";

	private DWGameManager()
	{
		s_traffic_amount_last = TrafficStats.getUidRxBytes(android.os.Process.myUid())
				+ TrafficStats.getUidTxBytes(android.os.Process.myUid());
		m_resourceDynamic = new Resource();
		m_resourceStatic = new Resource();
	}

	public static DWGameManager getInstance()
	{
		if (sInstance == null) {
			sInstance = new DWGameManager();
		}
		return sInstance;
	}

	public DWScreen getScreen()
	{
		return m_screen;
	}

	public void setScreen(DWScreen screen)
	{
		this.m_screen = screen;
	}

	public GameMessage getSendMessage()
	{
		return m_sendMessage;
	}

	public DWDownloadManager getDownloadManager()
	{
		return m_download_manager;
	}

	public IGameHandler getGameHandler()
	{
		return m_gamehandler;
	}

	public void setGameHandler(IGameHandler handler)
	{
		if (this.m_gamehandler != null && this.m_gamehandler.isRunning())
			this.m_gamehandler.setRunning(false);
		this.m_gamehandler = handler;
		DWScreen.Instance.setGameHandler(handler);
	}

	public void setRunning(boolean running)
	{
		m_running = running;
	}

	public void startThread()
	{
		m_thread = new Thread(this);
		m_thread.start();
	}

	public void setGameState(int gameState)
	{
		m_gameState = gameState;
	}

	public int getGameState()
	{
		return m_gameState;
	}

	/**
	 * 跳转到指定的Activity
	 *
	 * @param from
	 * @param clazz
	 * @param top
	 */
	public void goToActivity(Activity from, Class<?> clazz, boolean top)
	{
		Intent intent = new Intent(from, clazz);
		if (top) {
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		}
		from.startActivity(intent);
	}

	public DWGameActivity getCurrentActivity()
	{
		return m_currentActivity;
	}

	public DWGameView getGameView()
	{
		if (m_currentActivity != null)
			return m_currentActivity.getGameView();
		return null;
	}

	public DWInputView getInputView()
	{
		if (m_currentActivity != null)
			return m_currentActivity.getInputView();
		return null;
	}

	public String getInputString()
	{
		if (m_currentActivity.getInputView().getText() != null) {
			return m_currentActivity.getInputView().getText().toString();
		}
		return "";
	}

	/**
	 * 设置当前activity
	 *
	 * @param currentActivity
	 */
	public void setCurrentActivity(DWGameActivity currentActivity)
	{
		m_currentActivity = currentActivity;
	}

	public void flush()
	{
		Canvas canvas = null;
		SurfaceView view = m_currentActivity.getGameView();
		try {
			canvas = view.getHolder().lockCanvas();
			synchronized (view.getHolder()) {
				if (canvas != null) {
					getScreen().paint(canvas);
				}
			}
		}
		catch (Exception e) {
			Tools.debug(e);
		}
		finally {
			try {
				if (canvas != null) {
					view.getHolder().unlockCanvasAndPost(canvas);
				}
			}
			catch (Exception e) {
				Tools.debug(e);
			}
		}
	}

	/**
	 * 获得当前使用内存
	 *
	 * @return
	 */
	public static long getJavaHeap()
	{
		return Runtime.getRuntime().totalMemory()
				- Runtime.getRuntime().freeMemory();
	}

	public void initResource()
	{

	}

	public void pause()
	{
		if (m_gamehandler != null) {
			m_gamehandler.pause();
		}
	}

	public void resume()
	{
		if (m_gamehandler != null) {
			m_gamehandler.resume();
		}
	}

	public void stop()
	{
		if (m_gamehandler != null) {
			m_gamehandler.stop();
		}
		m_isPainting = false;
		DWAudio.getInstance().pauseMusic();
		DWAudio.getInstance().setSEPause(true);
	}

	public void start()
	{
		if (m_gamehandler != null) {
			m_gamehandler.start();
		}
		m_isPainting = true;
		DWAudio.getInstance().resumeMusic();
		DWAudio.getInstance().setSEPause(false);
	}

	public void destroy()
	{
		if (m_gamehandler != null) {
			m_gamehandler.destroy();
		}
		else {
			m_currentActivity.finish();
		}
		setRunning(false);
	}

	public static SharedPreferences s_config;
	public static SharedPreferences s_setting;
	public static SharedPreferences s_adpater;
	public static SharedPreferences s_halfRes;//半资源

	/**
	 * 初始化
	 */
	public void init()
	{
		createConnection(SERVER_URL, SERVER_PORT);
		m_download_manager = new DWDownloadManager();
		//读取配置
		readConfig();
		//读取设置
		readSetting();
		//读取适配
		readAdpater();
		//读取补充资源
		readHalfRes();
//		readSettingFromProperties(PROPERTIES_DIR);
//		setGameState(GS_TEST);
//		Test test = new Test();
//		setGameHandler(test);
		setGameState(GS_RESOURCE);
		ResourceVerifier rv = new ResourceVerifier();
		setGameHandler(rv);
	}

	public void run()
	{
//		android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_DISPLAY);

		long tick;

		try {
			init();
			while (m_running) {
				while (m_pause) {
					Thread.yield();
					continue;
				}
				tick = System.currentTimeMillis() + FRAME_INTERVAL;
				switch (m_gameState) {
					case GS_TEST:
						if (m_gamehandler != null && m_gamehandler instanceof Test) {
							Tools.debugPrintln("测试：");
							m_gamehandler.run();
						}
						break;
					case GS_GAME:
						if (m_gamehandler != null && m_gamehandler instanceof Scene.SceneHandler) {
							Tools.debugPrintln("进入游戏：");
							m_gamehandler.run();
						}
						break;
					case GS_LOADING:
						if (m_gamehandler != null && m_gamehandler instanceof Loading) {
							Tools.debugPrintln("Loading：");
							m_gamehandler.run();
						}
						break;
					case GS_LOGIN:
						if (m_gamehandler != null && m_gamehandler instanceof Login) {
							Tools.debugPrintln("登陆界面：");
							m_gamehandler.run();
						}
						break;
					case GS_RESOURCE:
						if (m_gamehandler != null && m_gamehandler instanceof ResourceVerifier) {
							Tools.debugPrintln("资源校验：");
							m_gamehandler.run();
						}
						break;
				}
				while (System.currentTimeMillis() < tick) {
					Thread.yield();
				}
				m_frameCounter++;
			}
			DWAudio.getInstance().releaseMusic();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		sInstance = null;
		android.os.Process.killProcess(android.os.Process.myPid());
	}

	public boolean recvMessage(int type, byte[] body)
	{

		try {
			int order = BaseConnection.s_perseOrderID;
			Tools.debugPrintln("指令号： " + order);
			if (type == GameProtocol.CONNECTION_CREATE_FAILED) {
				dealForConnectionCreateFaile();
				Tools.debugPrintln("网络连接创建失败!");
				return false;
			}
			// 连接异常
			if (type == GameProtocol.CONNECTION_BROKEN) {
				dealForConnectionException();
				Tools.debugPrintln("网络连接被断开!");
				return false;
			}
			// 数据为空
			if (body == null) {
				Tools.debugPrintln("body为空!");
				return false;
			}

			ByteArrayInputStream bais = new ByteArrayInputStream(body);
			DataInputStream dis = new DataInputStream(bais);
			switch (order) {
				case GameProtocol.SC_HEARTBEAT:
					dealWorldTimer(dis);
					break;
//				case GameProtocol.SC_REQUEST_ROLE_MAILS:
//					Tools.debugPrintln("读取角色邮件");
//					if (m_role != null) {
//						m_role.recvRequestRoleMails(dis);
//					}
//					break;
				default:
					switch (m_gameState) {
						case GS_TEST:
						case GS_LOGIN:
						case GS_LOADING:
						case GS_GAME:
						case GS_LOGO:
						case GS_RESOURCE:
							if (m_gamehandler != null) {
								m_gamehandler.recvMessage(type, dis);
							}
							break;
					}
					break;
			}
			dis.close();
			bais.close();
		}
		catch (Exception e) {
			Tools.debug(e);
		}

		return false;
	}

	public static void dealForConnectionException(String title, String tip, String left, String right)
	{
		DWGameManager.getInstance().closeConnection();
		final DWMessageBox dwMB = new DWMessageBox(title, tip, left, right);
		dwMB.addListener(new DWListener() {

			public void OnDoubleClick()
			{
			}

			public void OnClick()
			{
				if (DWMessageBox.SOFTKEY_OK == dwMB.getResult()) {
					DWControlsManager.getInstance().removeControl(dwMB);
					switch (DWGameManager.getInstance().m_gameState) {
						case GS_GAME:
							if (DWGameManager.getInstance().m_gamehandler instanceof SceneHandler) {
								SceneHandler hander = (SceneHandler) DWGameManager.getInstance().m_gamehandler;
								hander.m_state = SceneHandler.STATE_WAIT;
								hander.openConnection();
							}
							else {
								Login login = new Login();
								DWGameManager.getInstance().setGameHandler(login);
								DWGameManager.getInstance().setGameState(DWGameManager.GS_LOGIN);
							}
							break;
						case GS_RESOURCE:
							ResourceVerifier resource = new ResourceVerifier();
							resource.setState(ResourceVerifier.LOGIC_Waite_Connection);
							DWGameManager.getInstance().setGameHandler(resource);
							DWGameManager.getInstance().setGameState(
									DWGameManager.GS_RESOURCE);
							break;
						default:
							Login login = new Login();
							DWGameManager.getInstance().setGameHandler(login);
							DWGameManager.getInstance().setGameState(
									DWGameManager.GS_LOGIN);
							break;
					}
				}
				else if (DWMessageBox.SOFTKEY_BACK == dwMB.getResult()) {
					DWControlsManager.getInstance().removeControl(dwMB);
					DWGameManager.getInstance().destroy();
				}
			}
		});
		DWControlsManager.getInstance().addControl(dwMB);
	}

	/**
	 * 处理连接异常
	 */
	public void dealForConnectionException()
	{
		m_disoff = false;
		if (m_img != null && DWControlsManager.getInstance().contains(m_img)) {
			DWControlsManager.getInstance().removeControl(m_img);
		}
		String tip = "";
		DWGameManager.getInstance().closeConnection();
		String left = "确定";
		String right = null;
		switch (DWGameManager.getInstance().m_gameState) {
			case GS_GAME:
				left = "重新连接";
				right = "退出";
				tip = "网络出现异常，请选择重新链接或者退出！";
				break;
			case GS_RESOURCE:
				tip = "网络出现异常，请返回重新登陆！";
				break;
			default:
				tip = "网络无法连接，请检查网络后重新进入游戏！";
				break;

		}
		final DWMessageBox dwMB = new DWMessageBox("网络断开", tip, left, right);
		switch (DWGameManager.getInstance().m_gameState) {
			case GS_GAME:
				dwMB.addListener(new DWListener() {

					public void OnDoubleClick()
					{
					}

					public void OnClick()
					{
						byte result = dwMB.getResult();
						if (DWMessageBox.SOFTKEY_OK == result) {
							if (DWGameManager.getInstance().m_gamehandler instanceof SceneHandler) {
								SceneHandler hander = (SceneHandler) DWGameManager.getInstance().m_gamehandler;
								hander.m_state = SceneHandler.STATE_WAIT;
								hander.openConnection();
							}
							else {
								Login login = new Login();
								DWGameManager.getInstance().setGameHandler(login);
								DWGameManager.getInstance().setGameState(DWGameManager.GS_LOGIN);
							}
						}
						else if (DWMessageBox.SOFTKEY_BACK == result) {
							DWControlsManager.getInstance().removeControl(dwMB);
							Login login = new Login();
							DWGameManager.getInstance().setGameHandler(login);
							DWGameManager.getInstance().setGameState(DWGameManager.GS_LOGIN);
						}
						m_disoff = true;
						m_start_times = System.currentTimeMillis();
					}
				});
				break;
			default:
				dwMB.addListener(new DWListener() {

					public void OnDoubleClick()
					{
					}

					public void OnClick()
					{
						if (DWMessageBox.SOFTKEY_OK == dwMB.getResult()) {
							DWControlsManager.getInstance().removeControl(dwMB);
							switch (DWGameManager.getInstance().m_gameState) {
								case GS_RESOURCE:
									ResourceVerifier resource = new ResourceVerifier();
									resource.setState(ResourceVerifier.LOGIC_Waite_Connection);
									DWGameManager.getInstance().setGameHandler(resource);
									DWGameManager.getInstance().setGameState(DWGameManager.GS_RESOURCE);
									break;
								default:
									Login login = new Login();
									DWGameManager.getInstance().setGameHandler(login);
									DWGameManager.getInstance().setGameState(DWGameManager.GS_LOGIN);
									break;
							}
						}
						m_disoff = true;
						m_start_times = System.currentTimeMillis();
					}
				});
				break;
		}
		DWControlsManager.getInstance().addControl(dwMB);
//		if (DWGameManager.getInstance().getGameState() != DWGameManager.GS_GAME) {
//			Login m_login = new Login();
////			m_login.m_res_name = null;
////			m_login.m_res_password = null;
//			m_login.m_register_name = null;
//			m_login.m_register_password1 = null;
//		}
	}

	/**
	 * 处理连接异常
	 */
	public void dealForConnectionCreateFaile()
	{
		DWGameManager.getInstance().closeConnection();
		String tip = "无法连接到服务器,请检查网络设置以及状态!";
		final DWMessageBox dwMB = new DWMessageBox("连接问题", tip, "重试", "退出");
		dwMB.addListener(new DWListener() {

			public void OnDoubleClick()
			{
			}

			public void OnClick()
			{
				if (DWMessageBox.SOFTKEY_OK == dwMB.getResult()) {
					DWControlsManager.getInstance().removeControl(dwMB);
					switch (DWGameManager.getInstance().m_gameState) {
						case GS_RESOURCE:
							ResourceVerifier resource = new ResourceVerifier();
							resource.setState(ResourceVerifier.LOGIC_Waite_Connection);
							DWGameManager.getInstance().setGameHandler(resource);
							DWGameManager.getInstance().setGameState(DWGameManager.GS_RESOURCE);
							break;
						default:
							Login login = new Login();
							DWGameManager.getInstance().setGameHandler(login);
							DWGameManager.getInstance().setGameState(DWGameManager.GS_LOGIN);
							break;
					}
				}
				else if (DWMessageBox.SOFTKEY_BACK == dwMB.getResult()) {
					DWGameManager.getInstance().destroy();
				}
			}
		});
		DWControlsManager.getInstance().addControl(dwMB);
	}

	public boolean m_distime = false;
	public boolean m_disoff = true;
	public long m_start_times = System.currentTimeMillis();

	/**
	 * 处理世界时间
	 *
	 * @param body
	 */
	public void dealWorldTimer(DataInputStream dis)
	{

		m_start_times = System.currentTimeMillis();
		try {
			long lastTime = dis.readLong();
			s_worldTimeServer = dis.readLong();
			long curTime = System.currentTimeMillis();
//			s_worldTimeDelay = s_worldTimeServer - curTime + (curTime - lastTime) / 2;
			s_worldTimeDelay = curTime - lastTime;
			//
			// Date data1 = new Date(s_worldTimeServer);
			// Date data2 = new Date(curTime);
			//
			// System.out.println("server time:" + data1.toString());
			// System.out.println("client time:" + data2.toString());
		}
		catch (Exception ex) {
			Tools.debug(ex);
		}
	}

	public void connectionTimeout()
	{
	}

	public void connectionCreated()
	{
	}

	public void connectionBroken()
	{
	}

	public boolean connectionIsAlive()
	{
		return m_connection != null && m_connection.isAlive();
	}

	public final BaseConnection getConnection()
	{
		return m_connection;
	}

	public final void openConnection()
	{
		if (m_connection != null) {
			m_connection.open();
		}
		else {
			createConnection(SERVER_URL, SERVER_PORT);
			m_connection.open();
		}
	}

	public final void closeConnection()
	{
		if (m_connection != null) {
			m_connection.close();
			m_connection = null;
		}
	}

	public final void setConnectionServiceInfo(String ip, int port)
	{
		SERVER_URL = ip;
		SERVER_PORT = port;
		if (m_connection != null) {
			m_connection.setServiceInfo(ip, port);
		}
	}

	/**
	 * 请求多个资源
	 *
	 * @param heads
	 */
	public void requestResource(Map<String, ResHead> heads)
	{
		if (heads.size() > 0) {
			Tools.debugPrintln("请求缺失资源：" + GameProtocol.CS_REQUEST_RESOURCE);
			getSendMessage().sendRequestResource(heads);
		}
	}

	public void recvResource(byte[] body)
	{
		try {
			ByteArrayInputStream bais = new ByteArrayInputStream(body);
			DataInputStream dis = new DataInputStream(bais);
			ResHead head;
			int num = dis.readShort();
			for (int i = 0; i < num; i++) {
				try {
					byte type = dis.readByte();
					String url = dis.readUTF();
					head = new ResHead(type, url, 1);
					int dataLength = dis.readInt();
					byte[] data = new byte[dataLength];
					dis.read(data);
					//存储资源
					ResourceManager.getInstance().writeResource(head, data);

					Tools.debugPrintln("接收到缺失资源名：" + url);
				}
				catch (Exception e) {
					Tools.debug(e);
				}
			}
			bais.close();
			dis.close();
		}
		catch (Exception ex) {
			Tools.debug(ex);
			Tools.debugPrintln("接收到缺失资源异常！！！");
		}
	}

	/**
	 * 创建连接 默认GameManager为子类
	 *
	 * @param receiver
	 * @throws Exception
	 */
	public void createConnection(String serverURL, int serverPort)
	{
		BaseConnection.s_recvPackageId = -1;
		if (_server_type) {
			m_connection = BaseConnection.createConnection(
					BaseConnection.CONNECTION_TYPE_HTTP, serverURL, serverPort,
					sInstance);
		}
		else {
			m_connection = BaseConnection.createConnection(
					BaseConnection.CONNECTION_TYPE_TCP, serverURL, serverPort,
					sInstance);
		}
	}

	//private int m_connectionIdle = 0; // 用于保持心跳的帧计数
	//private int m_keepAliveInterval = 300; // 心跳间隔
	private int m_timexintiao = 30;// 心跳间隔30秒
	private long m_start_time = 0;

	/**
	 * 保持连接（定时发心跳）
	 *
	 * @return
	 */
	public boolean keepConnectionAlive()
	{
		if (m_connection != null) {

			if (m_timexintiao > 0) {
				if (m_start_time == 0) {
					m_start_time = System.currentTimeMillis();// 读取时截取系统时间
				}
				long currentTime = System.currentTimeMillis();// 当前系统时间
				int index = (int) (m_timexintiao - (currentTime - m_start_time) / 1000);
				//Tools.debugPrintln("心跳时间："+index+"秒");
				if (index < 0) {
					m_connection.keepAlive();
					m_start_time = 0;
				}
			}
//			if (m_connectionIdle > 0) {
//				m_connectionIdle--;
//			}
//			else {
//				m_connection.keepAlive();
//				m_connectionIdle = m_keepAliveInterval;
//			}
			return true;
		}
		return false;
	}

	private int m_webtime = 0;
	private byte m_webindex = 0;
	public DWImageBox m_img;

	/**
	 * 网络连接不良时的提示
	 */
	public void networkisnotgood()
	{
		if (m_disoff) {

			if (System.currentTimeMillis() > m_start_times + 45000) {
				m_distime = true;
			}
			else {
				if (m_img != null && DWControlsManager.getInstance().contains(m_img)) {
					DWControlsManager.getInstance().removeControl(m_img);
				}
				m_distime = false;
			}
			if (m_distime) {

				final String text =
						"亲！您的网络不太稳定，请稍候";

				if (m_webtime < 20) {
					m_webtime++;
				}
				else {
					m_webtime = 0;
					if (m_webindex < 3) {
						m_webindex++;
					}
					else {
						m_webindex = 0;
					}
				}

				if (!DWControlsManager.getInstance().contains(m_img)) {

					m_img = new DWImageBox(DWGameManager.Screen_Width, DWGameManager.Screen_Height);
					m_img.addExternalDraw(new DWExternalDraw() {

						public void externalDraw(DWGraphics g, int x1, int y1)
						{
							// TODO Auto-generated method stub
							StringBuffer dotNum = new StringBuffer();
							dotNum.append(" .");
							for (int i = 0; i < m_webindex; i++) {
								dotNum.append(" .");
							}

							int w = (int) DWFont.getFont(DWFont.getDefaultFont().getFontSize()).stringWidth(
									text + dotNum) + 20;

							int h = DWFont.getDefaultFont().getHeight() + 10;

							int y = DWGameManager.Screen_Height - h >> 1;

							g.setColor(0xC0000000);
							g.setClip(0, 0, DWGameManager.Screen_Width,
									DWGameManager.Screen_Height);
							g.fillRoundRect(DWGameManager.Screen_Width - w >> 1, y, w, h, 5, 5);
							g.drawString(text + dotNum, 0xFFFFFFFF, DWGameManager.Screen_Width
									- (w - 20) >> 1, y + 5, 0);
						}

					});
					m_img.setTouch(false);
					DWControlsManager.getInstance().addControl(m_img);
				}
			}
		}
	}

	private static final boolean HTTP_SERVER = true; // http连接方式
	private static final boolean TCP_SERVER = false; // tcp连接方式

	public static boolean _server_type = TCP_SERVER;
	//#if socket_server_ip==0
	//# public static String SERVER_URL = "221.130.10.134";
	//#else
	public static String SERVER_URL = "221.130.10.134";
	//#endif

	//#ifdef socket_server_port
	//#expand public static int SERVER_PORT = %socket_server_port%;
	//#else
	public static int SERVER_PORT = 30000;
	//#endif
	// // 弹出消息框消息
	// ////////////////////////////////////////////////////////////////////

	public static final int SYSTEM_INFO_TYPE_A = 0; //提示消息  （显示在滚动条下面）
	public static final int SYSTEM_INFO_TYPE_B = 1;//随时间变化 Toast
	public static final int SYSTEM_INFO_TYPE_C = 2;//系统提示
	public static final int SYSTEM_INFO_TYPE_D = 3;// 点击即消失,不会随时间变化
	public static final int SYSTEM_INFO_TYPE_E = 4;// 系统消息,悬停在UI与场景之上
	public static final int SYSTEM_INFO_TYPE_F = 5;
	Toast toast;

	/**
	 * 添加各种系统信息
	 *
	 * @param type
	 * @param content
	 */
	public void addSystemInfo(int type, String content)
	{
		if (content == null)
			return;
		try {
			switch (type) {
				case SYSTEM_INFO_TYPE_A:
					if (((SceneHandler) DWGameManager.getInstance().getGameHandler()).m_scene != null) {
						(((SceneHandler) DWGameManager.getInstance().getGameHandler()).m_scene).addMessage(content,
								Tools.RED, Tools.BLACK);
					}
					break;
				case SYSTEM_INFO_TYPE_B:// 随时间变化 消失

					if (m_gameState == GS_GAME) {
						if (((SceneHandler) DWGameManager.getInstance().getGameHandler()).m_scene != null) {
							(((SceneHandler) DWGameManager.getInstance().getGameHandler()).m_scene).addMessageB(
									content, (byte) 0);
						}
					}
					else {
						showToast(content, 2000);
					}

					break;
				case SYSTEM_INFO_TYPE_C:
					ChatItem item = ChatItem.createChatItem(ChatItem.TYPE_XI, -1, "", "", content, (byte) 0, (byte) 0);
					m_role.addToChat(item);
					break;
				case SYSTEM_INFO_TYPE_D:// 点击即消失,不会随时间变化(点击窗体就消失)
					if (((SceneHandler) DWGameManager.getInstance().getGameHandler()).m_scene != null) {
						final DWMessageBox alertBox = new DWMessageBox(null, content, null, "确定");
						alertBox.addListener(new DWListener() {
							public void OnDoubleClick()
							{
							}

							public void OnClick()
							{
								DWControlsManager.getInstance().removeControl(alertBox);
							}
						});
						DWControlsManager.getInstance().addControl(alertBox);
					}
					break;
				case SYSTEM_INFO_TYPE_E:
					addSysMessage(content);
					break;
				case SYSTEM_INFO_TYPE_F:
					break;
			}
		}
		catch (Exception e) {
			Tools.debug(e);
		}

	}

	public ArrayList<String> m_sys_message; //系统发布的滚动消息
	public ArrayList<String> m_sys_world_message; //玩家发布的喇叭喊话
	public ArrayList<String> m_particle_message; //带粒子动画的喇叭喊话

	/**
	 * 加入到系统消息队列中，显示在场景及UI层之上
	 */
	public void addSysMessage(String content)
	{
		int type = getSysMessageType(content);
		switch (type) {
			case 0:
				if (m_sys_message == null) {
					m_sys_message = new ArrayList<String>();
				}
				m_sys_message.add(content);
				break;
			case 1:
			case 2:
			case 3:
			case 4:
				if (m_sys_world_message == null) {
					m_sys_world_message = new ArrayList<String>();
				}
				m_sys_world_message.add(content);
				break;
			case 99:
				if (m_particle_message == null) {
					m_particle_message = new ArrayList<String>();
				}
				m_particle_message.add(content);
				break;
			default:
				break;
		}
	}

	private int getSysMessageType(String content)
	{
		int type = -1;
		try {
			type = Integer.parseInt(content.substring(0, 2));
		}
		catch (Exception e) {
		}
		return type;
	}

	// 空方法以后会变 为了移植方便添加
	// begin

	public void addMessage(String messsage)
	{

	}

	// //////end
	public void showToast(final String msg, final int time)
	{

		handler.post(new Runnable() {

			public void run()
			{

				DWToast dwToast = new DWToast(DWGameManager.getInstance().getCurrentActivity().getContext());
				dwToast.setText(msg);
				dwToast.setDuration(time);
				dwToast.show();

//				Toast.makeText(DWGameManager.getInstance().getCurrentActivity()
//						.getContext(), msg, time).show();
			}
		});
	}

	public void checkInputMethod()
	{
//		if (getInputView() != null) {
//			Tools.debugPrintln("inputview state : " + getInputView().isInEditMode() + ":" + getInputView().isInputMethodTarget() + ":" + getInputView().isInTouchMode());
//		}
	}

	////////////////////////////////////////////
	//// 设置相关
	public static int s_setting_system = 0xffffffff, s_setting_graphic = 0xffffffff, s_setting_light = 50;

	public static final int 设置系统_世界频道 = 1;
	public static final int 设置系统_家族频道 = 1 << 1;
	public static final int 设置系统_队伍频道 = 1 << 2;
	public static final int 设置系统_私聊频道 = 1 << 3;
	public static final int 设置系统_阵营频道 = 1 << 4;
	public static final int 设置系统_游戏音乐 = 1 << 5;
	public static final int 设置系统_游戏音效 = 1 << 6;

	public static final int 设置画面_显示敌方玩家 = 1;
	public static final int 设置画面_显示友方玩家 = 1 << 1;
	public static final int 设置画面_显示其他玩家名称 = 1 << 2;
	public static final int 设置画面_显示其他玩家特效 = 1 << 3;
	public static final int 设置画面_显示战斗信息 = 1 << 4;

	public static final String SETTING_KEY_SYSTEM = "setting_system";
	public static final String SETTING_KEY_GRAPHICS = "setting_graphics";
	public static final String SETTING_KEY_LIGHT = "setting_light";

	public static void setSetting_system(int id, boolean value)
	{
		if (value) {
			s_setting_system |= id;
		}
		else {
			s_setting_system &= ~id;
		}
		s_setting.edit().putInt(SETTING_KEY_SYSTEM, s_setting_system).commit();

		if (id == 设置系统_游戏音乐) {
			if (value) {
				DWAudio.getInstance().playMusic();
			}
			else {
				DWAudio.getInstance().stopMusic();
			}
		}
	}

	public static boolean getSetting_system(int id)
	{
		return (s_setting_system & id) != 0;
	}

	public static void setSetting_graphics(int id, boolean value)
	{
		if (value) {
			s_setting_graphic |= id;
		}
		else {
			s_setting_graphic &= ~id;
		}
		s_setting.edit().putInt(SETTING_KEY_GRAPHICS, s_setting_graphic).commit();
	}

	public static boolean getSetting_graphics(int id)
	{
		return (s_setting_graphic & id) != 0;
	}

	//屏幕亮度
	public static void setSetting_light(int value)
	{
		if (value == s_setting_light)
			return;
		int light = value - 10;
		if (light <= 1) {
			light = 1;
		}
		s_setting_light = Tools.limit(light, 0, 100);
//		DWGameManager.getInstance().getCurrentActivity().setScreenBrightness(s_setting_light / 100.0f);
		s_setting.edit().putInt(SETTING_KEY_LIGHT, s_setting_light).commit();
	}

	public static int getSetting_light()
	{
		return s_setting_light;
	}

	public static void readSetting()
	{
		try {
			s_setting = DWGameManager.getInstance().getCurrentActivity().getSharedPreferences(
					SETTING_NAME, ContextWrapper.MODE_PRIVATE);
			s_setting_graphic = s_setting.getInt(SETTING_KEY_GRAPHICS, 0xffffffff);
			s_setting_system = s_setting.getInt(SETTING_KEY_SYSTEM, 0xffffffff);
			s_setting_light = s_setting.getInt(SETTING_KEY_LIGHT, 50);
		}
		catch (Exception e) {
			Tools.debugPrintln("读取设置文件失败！！！！");
			Tools.debug(e);
		}
	}

	public static final String PROPERTIES_DIR = "data/data/com.handinfo.android/files";

	public static void writeSettingToProperties(String url)
	{
		try {
			Properties properties = new Properties();
			properties.put("setting_system", String.valueOf(s_setting_system));
			properties.put("setting_graphics", String.valueOf(s_setting_graphic));
			properties.put("setting_light", String.valueOf(s_setting_light));
			File dir = new File(url);
			File file = new File(url + "/setting.properties");
			if (file.exists()) {
				file.delete();
			}
			if (!dir.exists()) {
				dir.mkdirs();
			}
			file.createNewFile();
			FileOutputStream fos = new FileOutputStream(file);
			properties.save(fos, "");
			fos.flush();
			fos.close();
		}
		catch (Exception e) {
			Tools.debug(e);
		}
	}

	public static void readSettingFromProperties(String url)
	{
		Properties properties = new Properties();
		try {
			File file = new File(url + "/setting.properties");
			if (!file.exists()) {
				return;
			}
			FileInputStream fis = new FileInputStream(file);
			properties.load(fis);
			s_setting_system = Integer.valueOf(properties.get("setting_system").toString());
			s_setting_graphic = Integer.valueOf(properties.get("setting_graphics").toString());
			s_setting_light = Integer.valueOf(properties.get("setting_light").toString());
			fis.close();
		}
		catch (Exception e) {
			Tools.debug(e);
		}
	}

	////设置相关
	//////////////////////////////////////////////

	//////////////////////////////////////////////
	//// 资源配置以及版本相关
	public static final String CONFIG_NAME = "handinfo";
	public static final String SETTING_NAME = "game_setting";
	public static final String SERVERLIST_NAME = "server_list";
	public static final String ADAPTER_NAME = "adapter";
	public static final String HALFRES_NAME = "halfres";

	public static final String DEFAULT_RES_DIR = "mnt/sdcard/xianyuanonline/res";
	public static final String DEFAULT_APK_DIR = "mnt/sdcard/xianyuanonline/apk";

	/* 资源路径 */
	public static String s_res_dir = DEFAULT_RES_DIR;
	/* APK路径 */
	public static String s_apk_dir = DEFAULT_APK_DIR;

	public static boolean s_firstLogin = true;

	public static String DIR_SDCARD = "mnt/sdcard/xianyuanonline";
	public static String DIR_DATA = "data/data/com.handinfo.android/files";
	public static final String RES = "/res";
	public static final String APK = "/apk";

	public static final String CFG_KEY_FIRST_LOGIN = "firstLogin";
	public static final String CFG_KEY_RES_DIR = "resDirectory";
	public static final String CFG_KEY_APK_DIR = "apkDirectory";
	public static final String CFG_KEY_RES_VERSION = "versions";

	/**
	 * 读取配置文件
	 */
	public static void readConfig()
	{
		try {
			s_config = DWGameManager.getInstance().getCurrentActivity().getSharedPreferences(
					CONFIG_NAME, ContextWrapper.MODE_PRIVATE);

			s_firstLogin = s_config.getBoolean(CFG_KEY_FIRST_LOGIN, true);
			if (s_firstLogin) {
				DIR_DATA = DWGameManager.getInstance().getCurrentActivity().getFilesDir().toString();
				//是否有sd卡
				File file = IORWFile.getSDCardDir();
				if (file.exists()) {
					DIR_SDCARD = file.getPath() + "/xianyuanonline";
				}
				boolean sdcard = file != null;
				if (sdcard) {
					s_res_dir = DIR_SDCARD + RES;
					s_apk_dir = DIR_SDCARD + APK;
				}
				else {
					s_res_dir = DIR_DATA + RES;
					s_apk_dir = DIR_DATA + APK;
				}
				s_config.edit().putString(CFG_KEY_RES_DIR, s_res_dir).commit();
				s_config.edit().putString(CFG_KEY_APK_DIR, s_apk_dir).commit();
			}
			else {
				s_res_dir = s_config.getString(CFG_KEY_RES_DIR, DEFAULT_RES_DIR);
				s_apk_dir = s_config.getString(CFG_KEY_APK_DIR, DEFAULT_APK_DIR);
			}
		}

		catch (Exception e) {
			Tools.debugPrintln("读取配置文件失败！！！！");
			Tools.debug(e);
			try {
				boolean sdcard = IORWFile.getSDCardDir() != null;
				if (sdcard) {
					s_res_dir = DIR_SDCARD + RES;
					s_apk_dir = DIR_SDCARD + APK;
				}
				else {
					s_res_dir = DIR_DATA + RES;
					s_apk_dir = DIR_DATA + APK;
				}
				s_config.edit().putString(CFG_KEY_RES_DIR, s_res_dir).commit();
				s_config.edit().putString(CFG_KEY_APK_DIR, s_apk_dir).commit();
			}
			catch (Exception ex) {
				Tools.debugPrintln("解决配置文件问题失败！！！！");
				Tools.debug(e);
			}
		}
	}

	//读取适配信息
	public void readAdpater()
	{
		s_adpater = DWGameManager.getInstance().getCurrentActivity().getSharedPreferences(
				ADAPTER_NAME, ContextWrapper.MODE_PRIVATE);
		AdpaterValue = s_adpater.getInt(ADAPTER_NAME, 0);
	}

	//读取半资源信息
	public void readHalfRes()
	{
		s_halfRes = DWGameManager.getInstance().getCurrentActivity().getSharedPreferences(
				HALFRES_NAME, ContextWrapper.MODE_PRIVATE);
		Half_res = s_halfRes.getBoolean(HALFRES_NAME, false);
	}

	//// 资源配置以及版本相关
	////////////////////////////////////////////////////////////////

	///////////////道具缓存/////////////////////////////////////////
	public final int CACHE_MAX_NUM = 400;
	//通过KEY查询道具缓存
	public Hashtable<String, Item> m_cacheItemByKey = new Hashtable<String, Item>();
	//通过ID查询道具缓存
	public Hashtable<Long, Item> m_cacheItemByGuid = new Hashtable<Long, Item>();

	public Item getItemFormCacheByKey(String key)
	{
		Item item = null;
		if (m_cacheItemByKey != null && m_cacheItemByKey.containsKey(key)) {
			item = m_cacheItemByKey.get(key);
		}
		return item;
	}

	public void putItemForCacheByKey(Item item)
	{
		if (item != null && m_cacheItemByKey != null) {
			int size = m_cacheItemByKey.size();
			if (size >= CACHE_MAX_NUM) {
				m_cacheItemByKey.clear();
			}
			m_cacheItemByKey.put(item.m_key, item);
		}
	}

	public Item getItemFormCacheByGuid(long guid)
	{
		Item item = null;
		Long t = Long.valueOf(guid);
		if (m_cacheItemByGuid != null && m_cacheItemByGuid.containsKey(t)) {
			item = m_cacheItemByGuid.get(t);
		}
		return item;
	}

	public void putItemForCacheByGuid(Item item)
	{
		if (item != null && m_cacheItemByGuid != null) {
			int size = m_cacheItemByGuid.size();
			if (size >= CACHE_MAX_NUM) {
				m_cacheItemByGuid.clear();
			}
			Long t = Long.valueOf(item.m_guid);
			m_cacheItemByGuid.put(t, item);
		}
	}

	public boolean SeeItemInfos(String key, long guid)
	{
		Item item = null;
		if (guid > 0) {
			item = getItemFormCacheByGuid(guid);
		}
		if (item == null && key != null && !key.equals("")) {
			item = getItemFormCacheByKey(key);
		}
		if (item == null) {
			return false;
		}
		else {
			UIWindows.getInstance().m_bag.showItemMessage(item);
			if (DWControlsManager.getInstance().contains(UIWindows.getInstance().m_fuben.m_lose_frame)) {
				if (UIWindows.getInstance().m_fuben.m_lose_frame != null) {
					for (int i = 0; i < UIWindows.getInstance().m_fuben.size1 + UIWindows.getInstance().m_fuben.size2
							+ UIWindows.getInstance().m_fuben.size3; i++) {
						UIWindows.getInstance().m_fuben.m_ima_bg[i]
								.setBackground(UIWindows.getInstance().m_fuben.m_cr_xxbj);
					}
				}
			}
			if (DWControlsManager.getInstance().contains(UIWindows.getInstance().m_tower.m_lose_frame))
			{
				if (UIWindows.getInstance().m_tower.m_lose_frame != null) {
					for (int i = 0; i < UIWindows.getInstance().m_tower.m_tower_list.get(0).m_itemsize; i++) {
						UIWindows.getInstance().m_tower.m_ima_bg[i]
								.setBackground(UIWindows.getInstance().m_tower.m_cr_xxxbj);
					}
				}
			}
			return true;
		}
	}
}
